package bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by IntelliJ
 * Author:熊磊
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {

        //1.创建一个线程池
        //2. 如果有客户连接,就创建一个线程与之通讯

        //ThreadPoolExecutor executor = new ThreadPoolExecutor();
        //executor.
        ExecutorService threadPool = Executors.newCachedThreadPool();


        //创建服务端
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了");

        while (true) {
            System.out.println("等待连接");
            //监听客户端连接
            Socket socket = serverSocket.accept();
            System.out.println("连接到了一个客户端");

            //创建一个线程,与之通讯
            threadPool.execute(() -> {
                handler(socket);
            });
        }

    }

    // 和客户端通讯的方法
    public static void handler(Socket socket) {
        try {
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();

            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                System.out.println(Thread.currentThread().getName() + "发送了一个信息");
                System.out.println(new String(bytes, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭与客户端的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
